package com.wsz.ucenter.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
 
public class IpUtils {
	/**
	 * 读取
	 * 
	 * @param rd
	 * @return
	 * @throws IOException
	 */
	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}
	
	/**
	 * 创建链接
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	private static JSONArray readJsonFromUrl(String url) throws IOException, JSONException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONArray json = JSONArray.parseArray(jsonText);
			return json;
		} finally {
			is.close();
		}
	}
 
	/**
	 * 获取城市信息
	 * 
	 * @param ip
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public static JSONArray Address(String ip)  {
		JSONArray json = null;
		try {
			json = readJsonFromUrl("http://freeapi.ipip.net/"+ip);
			return json;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}